//
//  ZCenterMyQRCodeViewController.m
//  shopSN
//
//  Created by chang on 16/7/9.
//  Copyright © 2016年 yisu. All rights reserved.
//

#import "ZCenterMyQRCodeViewController.h"

#import "UMSocial.h"

@interface ZCenterMyQRCodeViewController ()

/**
 * 二维码视图
 */

@end

@implementation ZCenterMyQRCodeViewController
#pragma mark - ==== 页面设置 =====
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"分享二维码";
    //self.mainMiddleView.backgroundColor = HEXCOLOR(0xdedede);
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, __kWidth, __kHeight-64)];
    imageView.image = MImage(@"huiyuanka");
    
    [self.view addSubview:imageView];
    
    UIImageView *myImageView = [[UIImageView alloc] initWithFrame:CGRectMake(__kWidth-160, 150, 130, 130)];
//    myImageView.backgroundColor = [UIColor redColor];
//    self.qrCodeView = myImageView;
    
    myImageView.image = self.qrCodeView.image;
    
    [self.view addSubview:myImageView];
    
    //初始化 中间视图 相关子视图
//    [self initSubViews:self.mainMiddleView];
}

//#pragma mark - 中间视图部分 相关子视图
//初始化相关子视图
//- (void)initSubViews:(UIView *)view {
//    UIView *subBGView = [[UIView alloc] initWithFrame:CGRectMake(20, (CGRectH(view)-360)/2, CGRectW(view)-40, 320)];
//    [view addSubview:subBGView];
////    subBGView.backgroundColor = __TestOColor;
//    
//    //1 昵称
//    UILabel *nickLb = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, CGRectW(subBGView)-40, 30)];
//    [subBGView addSubview:nickLb];
////    nickLb.backgroundColor = __TestGColor;
//    nickLb.font = MFont(14);
//    nickLb.textColor = HEXCOLOR(0x333333);
//    nickLb.textAlignment = NSTextAlignmentCenter;
//    nickLb.text = _nickNameStr;
//    
//    //2 二维码图片
//     _qrCodeView = [[UIImageView alloc] initWithFrame:CGRectMake((CGRectW(subBGView)-240)/2, (CGRectH(subBGView)-240)/2, 240, 240)];
//    [subBGView addSubview:_qrCodeView];
//    _qrCodeView.backgroundColor = HEXCOLOR(0xffffff);
//    
//    UIImage *qrcode =[self createNonInterpolatedUIImageFormCIImage:[self createQRForString:self.qrCodeStr] withSize:240.0f];
//    
//    UIImage *customQrcode = [self imageBlackToTransparent:qrcode withRed:60.0f andGreen:74.0f andBlue:89.0f];
//    self.qrCodeView.image = customQrcode;
//    // set shadow
//    self.qrCodeView.layer.shadowOffset = CGSizeMake(0, 2);
//    self.qrCodeView.layer.shadowRadius = 2;
//    self.qrCodeView.layer.shadowColor = [UIColor blackColor].CGColor;
//    self.qrCodeView.layer.shadowOpacity = 0.5;
//    
//    //3 说明文字
//    UILabel *noteLb = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectH(subBGView)-30, CGRectW(subBGView)-40, 30)];
//    [subBGView addSubview:noteLb];
////    noteLb.backgroundColor = __TestGColor;
//    noteLb.font = MFont(12);
////    noteLb.textColor = HEXCOLOR(0x333333);
//    noteLb.textAlignment = NSTextAlignmentCenter;
//    noteLb.text = @"用手机shopSN扫一扫二维码，加关注";//test
//    
//}

#pragma mark - 自定义导航栏
- (void)addNavigationBar {
    //返回按钮
    UIButton *backBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
    [backBtn setBackgroundImage:MImage(@"fanhui.png") forState:BtnNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:BtnTouchUpInside];
    
    UIBarButtonItem *backItem=[[UIBarButtonItem alloc]initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = backItem;
    
    
    //右侧按钮
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 22)];
    //rightBtn.backgroundColor = __DefaultColor;
    rightBtn.titleLabel.font = MFont(17);
    [rightBtn setTitle:@"分享" forState:BtnNormal];
    [rightBtn setTitleColor:__DefaultColor forState:BtnNormal];
    
    [rightBtn addTarget:self action:@selector(rightButtonAciton) forControlEvents:BtnTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

#pragma mark - 分享我的二维码
-(void)rightButtonAciton{
    NSLog(@"分享");
    
    NSString *urlStr = [NSString stringWithFormat:@"http://www.zzumall.com/public/vipcard/%@.png",[UdStorage getObjectforKey:Userid]];
    
    [UMSocialData defaultData].extConfig.title =[NSString stringWithFormat:@"%@-二维码分享",simpleTitle] ;
    
    //微信好友 朋友圈 分享
    [UMSocialData defaultData].extConfig.wechatSessionData.url = urlStr;
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = urlStr;
    
    //qq好友 qq空间 分享
    [UMSocialData defaultData].extConfig.qqData.url = urlStr;
    [UMSocialData defaultData].extConfig.qzoneData.url = urlStr;
    [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeImage url:urlStr];
    
    
    
    [UMSocialSnsService presentSnsIconSheetView:self appKey:@"57f0ddcd67e58ea6b800526b" shareText:[NSString stringWithFormat:@"%@-二维码分享",simpleTitle] shareImage:nil shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToQQ,UMShareToQzone] delegate:nil];
    
   
}




#pragma mark - InterpolatedUIImage
//2 因为生成的二维码是一个CIImage，我们直接转换成UIImage的话大小不好控制，所以使用下面方法返回需要大小的UIImage
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // create a bitmap image that we'll draw into a bitmap context at the desired size;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // Create an image with the contents of our bitmap
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    // Cleanup
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

#pragma mark - QRCodeGenerator
//1 先是二维码的生成，使用CIFilter很简单，直接传入生成二维码的字符串即可
- (CIImage *)createQRForString:(NSString *)qrString {
    // Need to convert the string to a UTF-8 encoded NSData object
    NSData *stringData = [qrString dataUsingEncoding:NSUTF8StringEncoding];
    // Create the filter
    CIFilter *qrFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // Set the message content and error-correction level
    [qrFilter setValue:stringData forKey:@"inputMessage"];
    [qrFilter setValue:@"M" forKey:@"inputCorrectionLevel"];
    // Send the image back
    return qrFilter.outputImage;
}

#pragma mark - imageToTransparent
//3 因为生成的二维码是黑白的，所以还要对二维码进行颜色填充，并转换为透明背景，使用遍历图片像素来更改图片颜色，因为使用的是CGContext，速度非常快：
void ProviderReleaseData (void *info, const void *data, size_t size){
    free((void*)data);
}
- (UIImage*)imageBlackToTransparent:(UIImage*)image withRed:(CGFloat)red andGreen:(CGFloat)green andBlue:(CGFloat)blue{
    const int imageWidth = image.size.width;
    const int imageHeight = image.size.height;
    size_t      bytesPerRow = imageWidth * 4;
    uint32_t* rgbImageBuf = (uint32_t*)malloc(bytesPerRow * imageHeight);
    // create context
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(rgbImageBuf, imageWidth, imageHeight, 8, bytesPerRow, colorSpace,
                                                 kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipLast);
    CGContextDrawImage(context, CGRectMake(0, 0, imageWidth, imageHeight), image.CGImage);
    // traverse pixe
    int pixelNum = imageWidth * imageHeight;
    uint32_t* pCurPtr = rgbImageBuf;
    for (int i = 0; i < pixelNum; i++, pCurPtr++){
        if ((*pCurPtr & 0xFFFFFF00) < 0x99999900){
            // change color
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[3] = red; //0~255
            ptr[2] = green;
            ptr[1] = blue;
        }else{
            uint8_t* ptr = (uint8_t*)pCurPtr;
            ptr[0] = 0;
        }
    }
    // context to image
    CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rgbImageBuf, bytesPerRow * imageHeight, ProviderReleaseData);
    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, 8, 32, bytesPerRow, colorSpace,
                                        kCGImageAlphaLast | kCGBitmapByteOrder32Little, dataProvider,
                                        NULL, true, kCGRenderingIntentDefault);
    CGDataProviderRelease(dataProvider);
    UIImage* resultUIImage = [UIImage imageWithCGImage:imageRef];
    // release
    CGImageRelease(imageRef);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    return resultUIImage;
}



#pragma mark - ==== others =====
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
